package com.item.config;

import com.item.filter.HttpServletFilter;
import com.item.xss.XssFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang-rongyao
 * @version V1.0
 * @Package com.item.model.config
 * @date 2021/7/26 10:36
 */
@ServletComponentScan("com.item.filter")
@Configuration
public class FilterConfig {

    /**
     * 解决requestBody只能读取一次
     * @return
     */
    @Bean
    public FilterRegistrationBean<HttpServletFilter> registerFilter() {
        FilterRegistrationBean<HttpServletFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new HttpServletFilter());
        registration.addUrlPatterns("/*");
        registration.setName("orderFilter");
        //值越小，Filter越靠前。 但是有时候这个setOrder(1)不一定生效，所以一定要setName
        registration.setOrder(2);
        return registration;
    }

    //如果有多个Filter，再写一个public FilterRegistrationBean registerOtherFilter(){...}即可。

    /**
     * xss过滤拦截器
     * @return
     */
    @Bean
    public FilterRegistrationBean<XssFilter> registerXssFilter() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setEnabled(true);
        registration.setName("xssFilter");
        //值越小，Filter越靠前。 但是有时候这个setOrder(1)不一定生效，所以一定要setName
        registration.setOrder(0);
        Map<String, String> initParameters = new HashMap<>();
        //excludes用于配置不需要参数过滤的请求url
        initParameters.put("excludedPages", "/favicon.ico,/img/*,/js/*,/css/*");
        //isIncludeRichText主要用于设置富文本内容是否需要过滤
        //initParameters.put("isIncludeRichText", "true");
        registration.setInitParameters(initParameters);
        return registration;
    }



}
